"""
病历数据模型
"""
import uuid
from datetime import datetime
from typing import List, Optional
from sqlalchemy import (
    Column, String, Integer, Text, Boolean, TIMESTAMP,
    ARRAY, Index, text, ForeignKey
)
from sqlalchemy.dialects.postgresql import UUID, JSONB
from sqlalchemy.orm import relationship
from app.db.session import Base


class MedicalRecord(Base):
    """病历表"""
    __tablename__ = "medical_records"
    
    # 主键
    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    
    # 基本信息
    hospital_name = Column(String(200), nullable=True, comment="医院名称")
    record_type = Column(String(50), default="门诊病历", comment="病历类型")
    
    # 患者信息（结构化）
    patient_name = Column(String(100), nullable=False, comment="患者姓名")
    patient_age = Column(Integer, nullable=True, comment="患者年龄")
    patient_gender = Column(String(10), nullable=True, comment="患者性别")
    patient_card_number = Column(String(100), nullable=True, comment="门诊卡号")
    patient_phone = Column(String(50), nullable=True, comment="联系电话")
    patient_address = Column(Text, nullable=True, comment="现住址")
    department = Column(String(100), nullable=True, comment="科室")
    visit_date = Column(TIMESTAMP, nullable=True, comment="就诊日期")
    
    # 病情信息（结构化）
    chief_complaint = Column(Text, nullable=True, comment="主诉")
    present_illness = Column(Text, nullable=True, comment="现病史")
    allergy_history = Column(Text, nullable=True, comment="过敏史")
    past_history = Column(Text, nullable=True, comment="既往史")
    personal_history = Column(Text, nullable=True, comment="个人史")
    menstrual_history = Column(Text, nullable=True, comment="月经史")
    physical_exam = Column(Text, nullable=True, comment="体格检查")
    auxiliary_exam = Column(Text, nullable=True, comment="辅助检查")
    diagnosis = Column(ARRAY(Text), nullable=True, comment="诊断列表")
    
    # 医生信息
    doctor_name = Column(String(100), nullable=True, comment="医生姓名")
    
    # 原始JSON数据（完整保留）
    raw_data = Column(JSONB, nullable=False, comment="原始JSON数据")
    
    # 元数据
    created_at = Column(
        TIMESTAMP,
        nullable=False,
        server_default=text("CURRENT_TIMESTAMP"),
        comment="创建时间"
    )
    updated_at = Column(
        TIMESTAMP,
        nullable=False,
        server_default=text("CURRENT_TIMESTAMP"),
        onupdate=datetime.now,
        comment="更新时间"
    )
    uploaded_by = Column(String(100), nullable=True, comment="上传者")
    
    # 软删除标记
    is_deleted = Column(Boolean, default=False, comment="是否删除")
    
    # 关系
    medications = relationship(
        "Medication",
        back_populates="record",
        cascade="all, delete-orphan"
    )
    instructions = relationship(
        "Instruction",
        back_populates="record",
        cascade="all, delete-orphan"
    )
    assessments = relationship(
        "Assessment",
        back_populates="record",
        cascade="all, delete-orphan"
    )
    
    # 索引
    __table_args__ = (
        Index("idx_medical_records_patient_name", "patient_name"),
        Index("idx_medical_records_visit_date", "visit_date"),
        Index("idx_medical_records_department", "department"),
        Index("idx_medical_records_created_at", "created_at"),
        # GIN索引用于JSONB全文搜索
        Index("idx_medical_records_raw_data", "raw_data", postgresql_using="gin"),
    )
    
    def __repr__(self):
        return f"<MedicalRecord(id={self.id}, patient={self.patient_name})>"


class Medication(Base):
    """用药表"""
    __tablename__ = "medications"
    
    # 主键
    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    
    # 外键
    record_id = Column(
        UUID(as_uuid=True),
        ForeignKey("medical_records.id", ondelete="CASCADE"),
        nullable=False,
        comment="病历ID"
    )
    
    # 用药信息
    medication_name = Column(String(500), nullable=False, comment="药品名称")
    category = Column(String(100), nullable=True, comment="药品分类")
    specification = Column(String(200), nullable=True, comment="规格")
    route = Column(String(50), nullable=True, comment="给药途径")
    frequency = Column(String(50), nullable=True, comment="频次")
    dosage_value = Column(Integer, nullable=True, comment="剂量数值")
    dosage_unit = Column(String(20), nullable=True, comment="剂量单位")
    duration = Column(Integer, nullable=True, comment="用药天数")
    total_quantity = Column(String(100), nullable=True, comment="总量")
    
    # 原始数据
    raw_medication_data = Column(JSONB, nullable=True, comment="原始用药数据")
    
    # 元数据
    created_at = Column(
        TIMESTAMP,
        nullable=False,
        server_default=text("CURRENT_TIMESTAMP")
    )
    
    # 关系
    record = relationship("MedicalRecord", back_populates="medications")
    
    # 索引
    __table_args__ = (
        Index("idx_medications_record_id", "record_id"),
        Index("idx_medications_name", "medication_name"),
    )


class Instruction(Base):
    """医嘱表"""
    __tablename__ = "instructions"
    
    # 主键
    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    
    # 外键
    record_id = Column(
        UUID(as_uuid=True),
        ForeignKey("medical_records.id", ondelete="CASCADE"),
        nullable=False,
        comment="病历ID"
    )
    
    # 医嘱内容
    instruction_text = Column(Text, nullable=False, comment="医嘱内容")
    instruction_type = Column(String(50), nullable=True, comment="医嘱类型")
    
    # 元数据
    created_at = Column(
        TIMESTAMP,
        nullable=False,
        server_default=text("CURRENT_TIMESTAMP")
    )
    
    # 关系
    record = relationship("MedicalRecord", back_populates="instructions")
    
    # 索引
    __table_args__ = (
        Index("idx_instructions_record_id", "record_id"),
    )

